<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/13
 * Time: 17:04
 * Created by Created by Panxsoft.
 */

namespace App\Models;

use App\Models\Concerns\ModelMemorable;
use App\Services\MobileApp\AppEnv;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * @method Builder whereStatus
 * Class Language
 *
 * @property int language_id - primary key
 * @property string code
 *
 * @package App\Models
 * @mixin Builder
 */
class Language extends Model
{
    use ModelMemorable;

    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;

    const LANGUAGE_ZH_CN_ID = 2;
    const LANGUAGE_EN_GB_ID = 1;

    /**
     * 常量名应与目录 resources\lang\{dir_name} 中的 dir_name 对应
     */
    const CODE_FALLBACK = "zh-cn"; // 无法找到对应 CODE 时的默认语言

    protected $guarded = [];

    protected $table = 'language';

    protected $primaryKey = 'language_id';

    public static function allStatusEnable()
    {
        //languages - 获取系统所有语言
        return (new self)->where('status', self::STATUS_ENABLE)->get();
    }

    /**
     * @deprecated - 直接用 AppEnv::languageId()
     *
     * @return int
     */
    public static function getLanguageId()
    {
        return AppEnv::languageId();
    }

    /**
     * @param $store_id
     * @return mixed
     */
    public static function getStoreSettingLanguageCode(int $store_id = Store::STORE_ID_DEFAULT)
    {
        $settings =  Setting::findConfigByCode(Setting::CODE_CONFIG, $store_id);
        if (isset($settings['config_language'])) {
            return $settings['config_language'];
        } else {
            throw new \LogicException("Store [$store_id] config language missing");
        }
    }

    /**
     * @param $store_id
     * @return mixed
     */
    public static function getStoreDefault(int $store_id = Store::STORE_ID_DEFAULT): self
    {
        $code = self::getStoreSettingLanguageCode($store_id);
        if ($first = self::memoWhereFirst(compact('code'))) {
            return $first;
        } else {
            throw new \LogicException("Store [$store_id] Language code [$code] missing in database");
        }
    }

    /**
     * @param string $code
     *
     * @return Language|null
     */
    public static function findByCode(string $code): ?self
    {
        return (new self)->where(compact('code'))->first();
    }
}
